package org.wizehack.mri;

import java.io.File;

import org.wizehack.mri.CoverageDataParser.CoverageFileReader;
import org.wizehack.mri.CoverageDataParser.Line;
import org.wizehack.mri.CoverageDataParser.SourceFile;
import org.wizehack.mri.CoverageDataParser.SourceFileList;
import org.wizehack.mri.repo.MongoDBAccessPoint;
import org.wizehack.mri.test.TestCase;
import org.wizehack.mri.test.TestSuite;

import com.mongodb.DBObject;

public class CoverageWriterThread implements Runnable {
	
	private int testSuiteNumber;
	private TestSuite testSuite;
	private MongoDBAccessPoint dbap = MongoDBAccessPoint.getInstance();

	public CoverageWriterThread(int testSuiteNumber, TestSuite testSuite){
		this.testSuiteNumber = testSuiteNumber;
		this.testSuite = testSuite;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int i=0; i<testSuite.size(); i++){
			int testCaseNumber = i + 1;
			TestCase tc = testSuite.get(i);
			
			File covFile = new File(tc.getCoverageLocation());	
			CoverageFileReader cfr = new CoverageFileReader(covFile);
			SourceFileList sfList = cfr.getCoverage();
			
			for(int j=0; j<sfList.size(); j++){
				SourceFile sourceFile = sfList.get(j);
				String sourceFileName = sourceFile.getName();
				
				for(int k=0; k<sourceFile.size(); k++) {
					Line line = sourceFile.get(k);
					int num = line.getLineNumber();
//					System.out.println("test case: " + testCaseNumber);

					if(line.isCovered()){
//						System.out.println(sourceFileName);
//						System.out.println(num);

						DBObject dObj = dbap.getDocumentFromSourceCode(sourceFileName, num);
						String srcId = dObj.get("_id").toString();
						String code = dObj.get("code").toString();;
						
						dbap.insertDataToCoverage(sourceFileName, srcId, num, code, testSuiteNumber, testCaseNumber);
					}
				} // end for l
			} // end for k
		} // end for j
	}

}
